#include "TextureManager.h"
#include <string.h>

#define TRUE 1
#define FALSE 0

TextureManager::TextureManager()
{
	count = 0;	
}

TextureManager::~TextureManager()
{
	for( int i = 0; i < count; i++)
	{
		delete keys[i];
	}
}

int TextureManager::LoadTexture(const char * filename)
{
	
	if( TextureExists(filename))
		return TRUE;
	printf("Loading %s\n", filename);
	int status=FALSE;	 								// Status Indicator
	
	glbmp_t * textureImage = NULL;
	// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
	if ((textureImage = LoadBMP(filename)))
	{
		printf("Load succeeded\n");
		status=TRUE;									// Set The Status To TRUE

		glGenTextures(1, &texture[count]);					// Create The Texture
		glBindTexture(GL_TEXTURE_2D, texture[count]);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
		glTexImage2D(GL_TEXTURE_2D, 0, 4, textureImage->width, textureImage->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureImage->rgb_data);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	
		keys[count] = new char[64];
		strcpy(keys[count], filename);
		count++;
	}
	return status;
}

void TextureManager::EnableTexture(const char * key)
{
	for(int i = 0; i < count; i++)
	{
		if(strcmp(key, keys[i]) == 0)
		{
			glBindTexture(GL_TEXTURE_2D, texture[i]);
			glEnable(GL_TEXTURE_2D);
		}
	}
}

void TextureManager::EnableTexture(GLuint i)
{
	glBindTexture(GL_TEXTURE_2D, i);
	glEnable(GL_TEXTURE_2D);
}

bool TextureManager::TextureExists(const char * key)
{
	for(int i = 0; i < count; i++)
	{
		if(strcmp(key, keys[i]) == 0)
		{
			return true;
		}
	}
	return false;
}

GLuint TextureManager::TextureIndex(const char * key)
{
	for(int i = 0; i < count; i++)
	{
		if(strcmp(key, keys[i]) == 0)
		{
			return texture[i];
		}
	}
	return texture[0];
}
	
glbmp_t * TextureManager::LoadBMP(const char *Filename)				// Loads A Bitmap Image
{
	if (!Filename)										// Make Sure A Filename Was Given
	{
		return NULL;									// If Not Return NULL
	}

	glbmp_t * bmp_out = new glbmp_t();
	glbmp_LoadBitmap(Filename, GLBMP_ANY_SIZE, bmp_out);				// Load The Bitmap And Return A Pointer
	return bmp_out;
}
